<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="dataForm.id ? '修改公告' : '新增公告'"
               :modal="false"
               class="user-dialog add-or-updata"
               width="50%"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               label-width="120px">
        <el-form-item prop="noticeType"
                      :rules="required()"
                      label="公告类型">
          <el-select v-model="dataForm.noticeType"
                     placeholder="状态">
            <el-option v-for="item in typeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="announcementSubject"
                      :rules="required()"
                      label="公告主题">
          <el-input v-model.trim="dataForm.announcementSubject"
                    maxlength="20"
                    placeholder="请输入公告主题"></el-input>
        </el-form-item>
        <el-form-item prop="announcementContent"
                      label="公告内容"
                      :rules="required()"
                      v-if="dataForm.noticeType === '1'">
          <el-input type="textarea"
                    :autosize="{ minRows: 3, maxRows: 4}"
                    maxlength="200"
                    show-word-limit
                    v-model="dataForm.announcementContent"
                    placeholder="请输入公告内容"></el-input>
        </el-form-item>

        <el-form-item prop="imageUrl"
                      label="图片上传"
                      :rules="required()"
                      v-if="dataForm.noticeType === '2'">
          <file-upload reg=".(png|jpeg|jpg)$"
                       title="上传图片"
                       ref="fileUpload"
                       uploadType="picture-card"
                       accept=".jpeg,.jpg,.png"
                       :limit="1"
                       v-model="dataForm.imageUrl"
                       :paramData="{bucketName:'announcement/images'}"
                       action="/springbootApi/system/oss/upload"
                       @success="successImgLoad"
                       @remove="handleImgRemove" />
        </el-form-item>
        <el-form-item prop="videoUrl"
                      label="视频上传"
                      :rules="required()"
                      v-if="dataForm.noticeType === '3'">
          <file-upload reg=".(mp4)$"
                       title="上传视频"
                       ref="fileUpload"
                       uploadType="file"
                       accept=".mp4"
                       :limit="1"
                       v-model="dataForm.videoUrl"
                       :paramData="{bucketName:'announcement/radio'}"
                       action="/springbootApi/system/oss/upload"
                       @success="successImgLoad1"
                       @remove="handleImgRemove1" />
        </el-form-item>
        <el-form-item label="文章内容"
                      v-if="dataForm.noticeType === '4'">
          <tinymce ref="tinymce"
                   :isEdit='!!dataForm.id' />
        </el-form-item>
        <el-form-item prop="status"
                      label="创建后同时发布">
          <el-switch v-model="dataForm.status"
                     active-color="rgb(0, 157, 255)"
                     inactive-color="rgb(224, 224, 224)">
          </el-switch>
        </el-form-item>
        <el-form-item prop="checkList"
                      :rules="required()"
                      label="推送方式">
          <el-checkbox-group v-model="dataForm.checkList"
                             @change="changeCheckbos">
            <el-checkbox :label="1"
                         disabled>系统</el-checkbox>
            <el-checkbox :label="2">短信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="pushPeople"
                      label="短信接收人"
                      :rules="required()"
                      v-if="selectPeople">
          <el-radio-group v-model="dataForm.pushPeople"
                          @change="changeValue">
            <el-radio label="1">全部人员</el-radio>
            <el-radio label="2">指定部门人员</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="dataForm.pushPeople === '2' && selectPeople">
          <!-- default-expand-all -->
          <el-tree v-loading="dataListLoading"
                   :data="dataList1"
                   show-checkbox
                   node-key="id"
                   ref="tree"
                   highlight-current
                   :props="defaultProps"
                   @check="checked">
          </el-tree>
        </div>
      </el-form>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t('cancel')}}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t('confirm')}}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import tinymce from '@/components/tinymce/tinymce'
import fileUpload from '@/components/file-upload/file-upload'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        deleteImgURL: '/system/oss/delete',
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addURL: 'tb/noticeAnnouncement/add', // 添加或修改接口，API地址
        updateURL: 'tb/noticeAnnouncement/revise', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '', // 导出接口，API地址
        publishUrl: ''
      },
      typeList: [
        { id: '1', name: '文字' },
        { id: '2', name: '图片' },
        { id: '3', name: '视频' },
        { id: '4', name: '文字+视频+图片' }
      ],
      visible: false,
      dataList1: [],
      dataForm: {
        noticeType: '1',
        status: '0',
        pushType: '',
        imageUrl: '',
        videoUrl: '',
        pushPeople: '',
        checkList: [1]
      },
      selectPeople: 0,
      departmentId: [],
      isNall: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  components: { tinymce, fileUpload },
  methods: {
    init (data) {
      console.log(data)
      if (data) {
        this.dataForm.id = data.id
        this.dataForm.announcementSubject = data.announcementSubject
        this.dataForm.announcementContent = data.announcementContent
        this.dataForm.status = data.status
        this.dataForm.noticeType = data.noticeType
        // this.dataForm.pushType = data.pushType
        if (data.pushType === '3') {
          this.dataForm.checkList = [1, 2]
          this.selectPeople = 1
          // this.departmentId = data.pushList.map((item) => {
          //   return item.userId
          // })
        }
      }
      this.visible = true
      this.$nextTick(() => {
        if (this.dataForm.id && this.dataForm.noticeType === '2') {
          this.$refs.fileUpload.init([])
          let list = []
          list.push({
            name: this.dataForm.announcementContent,
            url: this.dataForm.announcementContent
          })
          this.$refs.fileUpload.init(list)
        } else if (this.dataForm.id && this.dataForm.noticeType === '3') {
          this.$refs.fileUpload.init([])
          let list = []
          list.push({
            name: this.dataForm.announcementContent,
            url: this.dataForm.announcementContent
          })
          this.$refs.fileUpload.init(list)
        } else if (this.dataForm.id && this.dataForm.noticeType === '4') {
          const rests = this.dataForm.announcementContent || ''
          this.dataForm.announcementContent = rests
          this.$refs.tinymce.init(rests)
        }
      })
    },
    closeDialog () {
      this.dataForm.noticeType = '1'
      this.dataForm.announcementSubject = ''
      this.dataForm.announcementContent = ''
      this.dataForm.checkList = [1]
      this.dataForm.status = false
      this.dataForm.pushType = ''
      this.selectPeople = 0
      if (this.dataForm.type === '4') {
        this.$refs.tinymce.clear()
      }
      this.$emit('callBack')
      this.visible = false
    },
    successImgLoad (name, url) {
      this.dataForm.imageUrl = url
    },
    handleImgRemove (url) {
      this.dataForm.imageUrl = ''
      this.deleteData({
        url: this.mixinViewModuleOptions.deleteImgURL,
        paramData: { files: url.url },
        isLoading: false
      })
    },
    successImgLoad1 (name, url) {
      this.dataForm.videoUrl = url
    },
    handleImgRemove1 (url) {
      this.dataForm.videoUrl = ''
      this.deleteData({
        url: this.mixinViewModuleOptions.deleteImgURL,
        paramData: { files: url.url },
        isLoading: false
      })
    },
    changeValue (val) {
      if (val === '2') {
        this.dataListLoading = true
        this.$http.get('/system/sysDept/getDeptList').then(({ data: res }) => {
          if (res.code !== 0) {
            return
          }
          this.dataList1 = res.data
          if (!res.data.length) {
            this.dataList1.push({
              id: 0,
              name: this.$t('dept.parentNameDefault')
            })
          }
          this.dataListLoading = false
        })
      }
    },
    changeCheckbos () {
      if (this.dataForm.checkList.indexOf(2) !== -1) {
        this.selectPeople = 1
      } else {
        this.selectPeople = 0
        // this.dataForm.pushPeople = '1'
      }
    },
    getCheckMenuChildren (actionItem, allChildren, ids) {
      ids = ids || []
      let filterItem = []
      ids.push(actionItem.id)

      actionItem.children.map(childrenItem => {
        if (!allChildren) {
          filterItem = this.actionItems.filter(item => item === childrenItem.id)
        }

        if (filterItem.length || allChildren) {
          ids = this.getCheckMenuChildren(childrenItem, !!allChildren, ids)
        }
      })

      return ids
    },
    checked (node, key) {
      this.isNall = key.checkedKeys.length
      this.departmentId = this.getCheckMenuChildren(node, true)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            const url = this.dataForm.id
              ? this.mixinViewModuleOptions.updateURL
              : this.mixinViewModuleOptions.addURL
            let obj = {}
            if (!this.dataForm.id) {
              obj.status = this.dataForm.status ? '1' : '0'
              obj.announcementSubject = this.dataForm.announcementSubject
              obj.noticeType = this.dataForm.noticeType
              obj.textUrl = ''
              obj.pushList = []
              if (this.dataForm.noticeType === '1') {
                obj.announcementContent = this.dataForm.announcementContent
              }
              if (this.dataForm.noticeType === '2') {
                obj.announcementContent = this.dataForm.imageUrl
              } else if (this.dataForm.noticeType === '3') {
                obj.announcementContent = this.dataForm.videoUrl
              } else if (this.dataForm.noticeType === '4') {
                obj.announcementContent = this.$refs.tinymce.getContent()
                obj.textUrl = this.$refs.tinymce.getImagePath()
              }
              if (this.dataForm.checkList.length === 1) {
                obj.pushType = '1'
              } else {
                obj.pushType = '3'
              }
              if (this.dataForm.pushPeople === '2' && this.selectPeople) {
                obj.pushList = this.departmentId.map((item) => {
                  return { userId: item }
                })
              }
              this.$http.post(url, obj).then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg)
                }
                this.$message.success('新增成功')
                this.$emit('callBack')
                this.closeDialog()
              })
            } else {
              // obj.announcementContent = this.$refs.tinymce.getContent()
              obj.id = this.dataForm.id
              obj.status = this.dataForm.status
              obj.noticeType = this.dataForm.noticeType
              obj.announcementSubject = this.dataForm.announcementSubject
              obj.textUrl = ''
              if (this.dataForm.noticeType === '1') {
                obj.announcementContent = this.dataForm.announcementContent
              }
              if (this.dataForm.noticeType === '2') {
                obj.announcementContent = this.dataForm.imageUrl
              } else if (this.dataForm.noticeType === '3') {
                obj.announcementContent = this.dataForm.videoUrl
              } else if (this.dataForm.noticeType === '4') {
                obj.announcementContent = this.$refs.tinymce.getContent()
                obj.textUrl = this.$refs.tinymce.getImagePath()
              }
              if (this.dataForm.checkList.length === 1) {
                obj.pushType = '1'
              } else {
                obj.pushType = '3'
              }
              if (this.dataForm.pushPeople === '2' && this.selectPeople) {
                obj.pushList = this.departmentId.map((item) => {
                  return { userId: item }
                })
              }
              // obj.textUrl = this.$refs.tinymce.getImagePath()
              this.$http.put(url, obj).then(({ data: res }) => {
                if (res.code !== 0) {
                  return this.$message.error(res.msg)
                }
                this.$message.success('保存成功')
                this.$emit('callBack')
                this.closeDialog()
              })
            }
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped>
</style>
